package com.example.boardroom.demo.times;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.ArraySet;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.boardroom.R;
import com.example.boardroom.appusagestatistics.AppUsageStatisticsFragment;
import com.example.boardroom.demo.BaseActivity;
import com.example.boardroom.demo.HelloService;
import com.example.boardroom.demo.room.TimesTable;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.TimeZone;

public class TimesActivity extends BaseActivity {
    private AdapterTimes adapterTimes;
    private RecyclerView recyclerview;
    Button btn_upload;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_times);
        recyclerview = findViewById(R.id.recyclerview);
        btn_upload = findViewById(R.id.btn_upload);
        initAdapter();
        getTimes();
        getAllAppNames();
        if (!ServiceUtils.isServiceRunning(HelloService.class)) {
            ServiceUtils.startService(HelloService.class);
        }
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimes();
            }
        });
    }

    UsageStatsManager mUsageStatsManager;
    Calendar cal;

    private long bootTime() {
        return System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1000000;
    }

    private List<BeanTimes> data;

    private void initAdapter() {
        data = new ArrayList<>();
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapterTimes = new AdapterTimes(data);
        recyclerview.setAdapter(adapterTimes);
    }

    private void getTimes() {
        if (null != data && data.size() > 0) {
            data.clear();
        }
//        LogUtils.i("lufei_time",   "包名: "+usageStats.getPackageName() ,"开始时间: "+ TimeUtils.millis2String(usageStats.getFirstTimeStamp()) +"-----  结束时间: "+TimeUtils.millis2String(usageStats.getLastTimeStamp()),"启动次数: "+"1");
        String startupTime = TimeUtils.millis2String(System.currentTimeMillis() - SystemClock.elapsedRealtime());
        long startupTime_long = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        mUsageStatsManager = (UsageStatsManager) this
                .getSystemService(Context.USAGE_STATS_SERVICE); //Context.USAGE_STATS_SERVICE
        List<UsageStats> usageStatss = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, System.currentTimeMillis() - SystemClock.elapsedRealtime(), TimeUtils.getNowMills());
        Collections.sort(usageStatss, new LastTimeLaunchedComparatorDesc());
        for (UsageStats usageStats : usageStatss) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                LogUtils.i("lufei_time", "包名:" + usageStats.getPackageName(), "开始时间: " + TimeUtils.millis2String(usageStats.getFirstTimeStamp()) + "-----  结束时间: " + TimeUtils.millis2String(usageStats.getLastTimeStamp()), "启动次数: " + "1"
                        , "运行总时长 : " + usageStats.getTotalTimeVisible() / 1000 / 60 + "分钟", "开机时间:" + TimeUtils.millis2String(System.currentTimeMillis() - SystemClock.elapsedRealtime()), "从开机开始算，累计运行时间:" + (usageStats.getLastTimeStamp() - usageStats.getFirstTimeStamp()) / 1000 / 60 + "分钟"
                        , "反向计算出启动时间: " + TimeUtils.millis2String((usageStats.getLastTimeStamp() - usageStats.getTotalTimeVisible())) + "---- 结束时间: " + TimeUtils.millis2String(usageStats.getLastTimeStamp())
                        , "getTotalTimeInForeground: " + usageStats.getTotalTimeInForeground()
                        , "getTotalTimeVisible: " + usageStats.getTotalTimeVisible()
                        , "getTotalTimeForegroundServiceUsed: " + usageStats.getTotalTimeForegroundServiceUsed());
                if (usageStats.getTotalTimeVisible() > 0) {
                    data.add(new BeanTimes(usageStats, ""));

                }
            }
        }
        xxx(data);

    }

    private static class LastTimeLaunchedComparatorDesc implements Comparator<UsageStats> {

        @Override
        public int compare(UsageStats left, UsageStats right) {
            return Long.compare(right.getLastTimeUsed(), left.getLastTimeUsed());
        }
    }


    /**
     * 获取android设备中全部app名称和应用包名
     */
    public void getAllAppNames() {
        ArrayList customApps = new ArrayList<PackageInfo>(); // 普通应用程序列表
        ArrayList systemApps = new ArrayList<PackageInfo>(); // 系统应用程序列表
        // 得到PackageManager对象
        PackageManager pm = getPackageManager();
//        获取到所有安装了的应用程序的信息，包括那些卸载了的，但没有清除数据的应用程序
        List<PackageInfo> appList = pm.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);

        int j = 0;

        for (PackageInfo packageInfo : appList) {
            // 列出普通应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                customApps.add(packageInfo);
            }
            // 列出系统应用，总是感觉这里设计的有问题，希望高手指点
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                systemApps.add(packageInfo);
            }
            //得到手机上已经安装的应用的名字,即在AndriodMainfest.xml中的app_name。
            String appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            //得到手机上已经安装的应用的图标,即在AndriodMainfest.xml中的icon。
            Drawable drawable = packageInfo.applicationInfo.loadIcon(getPackageManager());
            //得到应用所在包的名字,即在AndriodMainfest.xml中的package的值。
            String packageName = packageInfo.packageName;
            Log.e("=======aaa", "应用的名字:" + appName);
            Log.e("=======bbbb", "应用的包名字:" + packageName);
            // 禁用
            // pm.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);

            j++;
        }
        Log.e("========cccccc", "应用的总个数:" + j);
        Log.e("========eeeeee", "普通应用总个数:" + customApps.size());
        Log.e("========dddddd", "系统应用总个数:" + systemApps.size());
        getApps();
    }

    private void getApps() {
        for (AppUtils.AppInfo appInfo : AppUtils.getAppsInfo()) {
            LogUtils.i("lufei_getApps", appInfo.getPackageName(), "是否是系统应用" + appInfo.isSystem());
        }
        LogUtils.i("lufei_getApps", AppUtils.getAppsInfo().size());
    }

    private void xxx(List<BeanTimes> data) {
        List<Object> list = new ArrayList<>();
        HashMap<String, Object> hashMap;
        for (BeanTimes datum : data) {
            hashMap = new HashMap<>();
            hashMap.put("deviceId", 1);
            hashMap.put("handleType", "1");
            hashMap.put("packageName", datum.usageStats.getPackageName());
            hashMap.put("handleStatus", AppUtils.isAppRunning(datum.usageStats.getPackageName()) ? "0" : "1");
            hashMap.put("handleFlag", AppUtils.isAppRunning(datum.usageStats.getPackageName()) ? "0" : "1");
            hashMap.put("appName", AppUtils.getAppName(datum.usageStats.getPackageName()));
            LogUtils.i("lufei_xxx", datum.usageStats.getPackageName(), AppUtils.isAppRunning(datum.usageStats.getPackageName()) ? "0" : "1", AppUtils.getAppName(datum.usageStats.getPackageName()));
            list.add(hashMap);
        }
        String s = GsonUtils.toJson(list);
        LogUtils.i("lufei_bbb", s);
        upLoadAppStatus(s);
    }

    /**
     * `deviceId` bigint(20) DEFAULT NULL COMMENT '设备ID',
     * `handleType` char(1) NOT NULL DEFAULT '0' COMMENT '操作类型（0本设备 1设备里的应用）',
     * `packageName` varchar(100) DEFAULT NULL COMMENT '包名称',
     * `appName` varchar(50) DEFAULT NULL COMMENT '包对应的应用名称',
     * `handleStatus` char(1) NOT NULL DEFAULT '0' COMMENT '处理状态（0开关流程开始 1开关流程结束）',
     * `handleFlag` char(1) NOT NULL DEFAULT '0' COMMENT '处理标志（0开 1关）',
     */
    private void upLoadAppStatus(String json) {

        OkGo.<String>post("http://192.168.1.26:19100/link/deviceUseLog/batchAddDeviceUseLog")
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }
}
